package com.bookstore.controller;

/**
 * @Author Cofe
 * @Date 2022/5/15 20:38
 */

import com.bookstore.service.impl.BookServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;

@Controller
@RequestMapping("/file")
@Slf4j
public class FileController {
    @Resource
    private BookServiceImpl bookService;
   // @ApiOperation("上传文件")
    @RequestMapping(
            value = "/uploading",
            method = RequestMethod.POST
    )
    @CrossOrigin
    @ResponseBody
    String uploadFile(@RequestParam("filename") MultipartFile file,String book_name) {
        log.info("接收到的文件数据为：" + file);
        if (file.isEmpty()) {
            return "上传文件为空";
        }
        // 获取文件全名a.py
        String fileName = file.getOriginalFilename();
        System.out.println(book_name);
        // 文件上传路径
        String templatePath = "D:\\ChaoPei\\JavaBaseo\\WebAppp\\bookshop2.1\\src\\assets\\img";
        log.info("文件路径:" + templatePath);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //获取文件名
        String prefixName = fileName.substring(0, fileName.lastIndexOf("."));
        System.out.println(prefixName);
        // 解决中文问题,liunx 下中文路径,图片显示问题
        //fileName = UUID.randomUUID() + suffixName;
        File dest0 = new File(templatePath);
        File dest = new File(dest0, File.separator + fileName);
        //文件上传-覆盖
        try {
            // 检测是否存在目录
            if (!dest0.getParentFile().exists()) {
                dest0.getParentFile().mkdirs();
                //检测文件是否存在
            }
            if (!dest.exists()) {
                dest.mkdirs();
            }
            file.transferTo(dest);

            return "上传成功";
        } catch (Exception e) {
            log.error("文件上传错误");
            return "上传失败";
        }
    }
}